package com.example.task;


import com.example.entity.Orders;
import com.example.mapper.OrderSubmitMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderSubmitMapper orderSubmitMapper;


    /**
     * 处理订单超时
     */
    @Scheduled(cron = "0 * * * * ? ") //每分钟执行一次
    //@Scheduled(cron = "0/5 * * * * ? ") //测试
    public void processTimeOut(){
        log.info("处理超时订单：{}",LocalDateTime.now());

        //当前时间减去15分钟
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderSubmitMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, localDateTime);

        if (ordersList!=null && ordersList.size()>0 ){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderSubmitMapper.update(orders);

            }

        }


    }
}
